package com.example.demo.mapper;


import com.example.demo.entity.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Optional;

@Mapper
public interface StudentMapper {

    String COLUMNS = "student_id, student_name, password, class_name, enrollment_year, created_at, updated_at";

    // 1. 查找所有学生
    @Select("SELECT " + COLUMNS + " FROM students")
    List<Student> findAll();

    // 2. 根据学号查找单个学生
    @Select("SELECT " + COLUMNS + " FROM students WHERE student_id = #{studentId}")
    Optional<Student> findById(@Param("studentId") String studentId);

    // 3. 根据班级名称查找学生
    @Select("SELECT " + COLUMNS + " FROM students WHERE class_name = #{className}")
    List<Student> findByClassName(@Param("className") String className);

    // 4. 根据入学年份查找学生
    @Select("SELECT " + COLUMNS + " FROM students WHERE enrollment_year = #{enrollmentYear}")
    List<Student> findByEnrollmentYear(@Param("enrollmentYear") Integer enrollmentYear);

    // 5. 插入新学生（注册）
    @Insert("INSERT INTO students (student_id, student_name, password, class_name, enrollment_year) " +
            "VALUES (#{studentId}, #{studentName}, #{password}, #{className}, #{enrollmentYear})")
    int insert(Student student);

    // 6. 更新学生信息
    @Update({
            "<script>",
            "UPDATE students",
            "SET updated_at = CURRENT_TIMESTAMP()",
            "<if test='studentName != null'>, student_name = #{studentName}</if>",
            "<if test='password != null'>, password = #{password}</if>", // 实际应用中需要先加密
            "<if test='className != null'>, class_name = #{className}</if>",
            "<if test='enrollmentYear != null'>, enrollment_year = #{enrollmentYear}</if>",
            "WHERE student_id = #{studentId}",
            "</script>"
    })
    int update(Student student);

    // 7. 根据学号删除学生
    @Delete("DELETE FROM students WHERE student_id = #{studentId}")
    int deleteById(@Param("studentId") String studentId);
}